<?php
namespace plugins\goods\controller;

use app\common\lib\model_operate\Transit;
use cmf\controller\ApiPluginBaseController;
use cmf\controller\PluginRestBaseController;
use plugins\goods\model\GoodsModel; //引入此类
use think\Db;
use think\Validate;
use plugins\store\model\StoreModel;

/**
 * api控制器
 */
class ApiIndexController extends ApiPluginBaseController
{
    protected $model; //模型
    protected $uid = '';
    protected $search_num = 10; //搜索记录展示条数

    /**
     * 初始化
     */
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new GoodsModel();
        $this->uid = $this->getIdentity()->uid;
    }

    /**
     * 参数非空验证
     */
    private function verify($field, $data)
    {
        $arr = [];
        foreach ($field as $key => $value) {
            $arr[$value] = 'require';
        }
        $validate = new Validate($arr);
        if (!$validate->check($data)) {
            return api_json_echo(false, $validate->getError(), null, -1);
        }
    }

    /**
     * 商品搜索记录
     */
    public function GoodsSearchRecord()
    {
        $data = $this->request->post();
        $list = $this->model->getSearchRecord( $this->uid , $this->search_num);
        return api_json_echo(true, 'success', $list, 200);
    }

    /**
     * 商品收藏列表
     */
    public function collectList()
    {
        $data = $this->request->post();
        $this->verify(['pageNum', 'page'], $data);

        $collect = db('goods_collect')->where('uid', $this->uid)->find();
        $gids = [];
        if (!empty($collect)) {
            $gids = preg_split('/[\,+]/u', $collect['goods_id'], null, PREG_SPLIT_NO_EMPTY); //拆分字符串
        }
        $list = $this->model->where('id', 'in', $gids)->paginate($data['pageNum'], false, ['page' => $data['page']])->toArray();

        return api_json_echo(true, 'success', $list, 200);
    }

    /**
     * 清除搜索记录
     */
    public function clearRecord()
    {
        $uid    = $this->uid;
        $search = Db::name('goods_search')->where('uid', $uid)->delete();
        return api_json_echo(true, '清除成功', null, 200);
    }

    /**
     * 添加收藏
     */
    public function collect()
    {
        $data = $this->request->post();
        $this->verify(['goods_id', 'type'], $data);
        $uid     = $this->uid;
        $collect = Db::name('goods_collect')->where('uid', $uid)->find();
        switch ($data['type']) {
            case 1: //添加收藏
                if (!empty($collect)) {
                    $coll = $collect['goods_id'] . "," . $data['goods_id'] . ",";
                    $da   = [
                        'goods_id' => $coll,
                    ];
                    Db::name('goods_collect')->where('uid', $uid)->update($da);
                } else {
                    $da = [
                        'uid'      => $uid,
                        'goods_id' => "," . $data['goods_id'] . ",",
                    ];
                    Db::name('goods_collect')->insert($da);
                }
                break;
            case 2: //取消收藏
                $coll = str_replace(',' . $data['goods_id'] . ',', "", $collect['goods_id']);
                $da   = [
                    'goods_id' => $coll,
                ];
                Db::name('goods_collect')->where('uid', $uid)->update($da);
                break;
            default:
                # code...
                break;
        }
        return api_json_echo(true, '操作成功', null, 200);
    }
    
    //店铺推荐商品
    public function recommendByStore()
    {
        $param    = $this->request->param();
        $sid      = isset($param['sid']) ? $param['sid'] : '';
        $page     = isset($param['page']) ? $param['page'] : 1;
        $pageSize = isset($param['pagesize']) ? $param['pagesize'] : 20;
        if (empty($sid)) {
            return api_json_echo(false, '店铺id不能为空', null, 101);
        }
        $list = GoodsModel::where('status', 1)
            ->where('store_id', $sid)->where('referr_status', 1)
            ->order('add_time desc')
            ->paginate($pageSize, false, ['query' => ['page' => $page]]);
        return api_json_echo(true, '成功', $list);
    }

    /**
     * 获取店铺id
     */
    private function getStoreId()
    {
        $uid = $this->uid;
        $store_id = db('store')->where('uid',$uid)->value('store_id');
        return $store_id;
    }

    /**
     * 店铺上架和下架的商品
     */
    public function storePutawayGoods()
    {
        $data = $this->request->post();
        $this->verify(['pageNum','page'], $data);
        $data['store_id'] = $this->getStoreId();
        $where = 1;
        $where .= " and is_del <> 1";
        $where .= " and store_id = '".$data['store_id']."'";
        $where .= " and audit_status = 2"; //审核通过的商品
        $order = "add_time desc";

        $all_goods = 0; //全部商品数量
        $shang_num = $this->model->where($where)->where('status',1)->count(); //商家商品数量
        $xia_num = $this->model->where($where)->where('status',2)->count(); //下架商品数量
        $list  = $this->model
            ->where($where)
            ->order($order)
            ->paginates($data['pageNum'], '', ['page' => $data['page']])
            ->each(function($item){
                $item['add_time'] = date('Y-m-d H:i:s',$item['add_time']);
                $item['goods_img'] = $item['goods_img'] ? zy_domain() . $item['goods_img'] : '';
                return $item;
            })->toArray();

        $list['all_goods'] = $shang_num + $xia_num;
        $list['shang_num'] = $shang_num;
        $list['xia_num'] = $xia_num;

        return api_json_echo(true, 'success', $list, 200);
    }


    /**
     * 店铺审核商品
     */
    public function storeAuditGoods()
    {
        $data = $this->request->post();
        $this->verify(['pageNum','page'], $data);
        $data['store_id'] = $this->getStoreId();
        $where = 1;
        $where .= " and is_del <> 1";
        $where .= " and store_id = '".$data['store_id']."'";
        $where .= " and audit_status not in (2,0) "; //获取待审核和审核失败的商品
        $order = "add_time desc";

        $all_goods = 0; //全部商品数量
        $wait_goods_num = $this->model->where($where)->where('audit_status', 1)->count(); //待审核商品数量
        $refuse_goods_num = $this->model->where($where)->where('audit_status', 3)->count(); //被驳回商品数量
        $list  = $this->model
            ->where($where)
            ->order($order)
            ->paginates($data['pageNum'], '', ['page' => $data['page']])
            ->each(function ($item){

                $item['add_time'] = date('Y-m-d H:i:s',$item['add_time']);
                $item['goods_img'] = $item['goods_img'] ? zy_domain() . $item['goods_img'] : '';
                return $item;
            })->toArray();
 
        $list['all_goods_num'] = $wait_goods_num + $refuse_goods_num;
        $list['wait_goods_num'] = $wait_goods_num;
        $list['refuse_goods_num'] = $refuse_goods_num;

        return api_json_echo(true, 'success', $list, 200);
    }

    /**
     * 商品上架
     */
    public function storeGoodsEditStatus()
    {
        $data = $this->request->post();
        $this->verify(['id','status'], $data);

        $id = explode(',',$data['id']);
        
        $upd = [];
        switch ($data['status']) {
            case 1: //上架
                $upd['status'] = 1;
                $upd['upward_time'] = time();
                break;
            case 2: //下架
                $upd['status'] = 2;
                $upd['dowm_time'] = time();
                break;
            default:
                return api_json_echo(false, '参数错误', null, 101);
                break;
        }

        $this->model->save(
            $upd,
            ['id' => ['in',$id]]
        );
        return api_json_echo(true, '操作成功', null, 200);
    }

    /**
     * 店铺审核商品删除
     */
    public function storeAuditGoodsDel()
    {
        $data = $this->request->post();
        $this->verify(['id'], $data);

        $id = explode(',',$data['id']);

        $this->model->save(
            ['is_del' => 1], ['id' => ['in', $id]]
        );

        return api_json_echo(true, '操作成功', null, 200);
    }

    /**
     * 店铺审核原因
     */
    public function storeAuditReason()
    {
        $data = $this->request->post();
        $this->verify(['id'], $data);

        $audit = db('audit')->where('goodsid',$data['id'])->order('time','desc')->find();

        $da = [
            'reason' => $audit['reason'],
            'time' => $audit['time'] ? date('Y-m-d H:i:s', $audit['time']) : '',
        ];

        return api_json_echo(true, '操作成功', $da, 200);
    }


}
